<?php

    class JokeController extends WebController
    {


        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array('index','view'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('create'),
                    'users'=>array('@'),
                ),

                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('update'),
                    'expression'    =>  array($this, 'ruleModOwner'), 
                ),

                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                    'actions'=>array('admin', 'fix', 'delete', 'reviewed','social'),
                    'users'=>array('@'),
                    'expression'    =>  '$user->userInfo->isMod', 
                ),
                array('deny',  // deny all users 
                    'users'=>array('*'),
                ),
            );
        }

        /**
        * Danh sách images
        * 
        * @param string $username username
        * @param string $type hiển thị theo kiểu: NULL: đã review lên top. 'review' : Chưa review lên top
        */
        public function actionIndex($username = NULL, $type = 'ok')
        {   
            $title = 'Truyện cười';

            $criteria=new CDbCriteria;
            if($type == 'ok'){
                $criteria->addCondition("t.`status` = 'APPROVED'");
                $criteria->order = "t.reviewed DESC";
            }
            elseif($type == 'review'){
                $criteria->addCondition("t.`reviewed` is NULL");
                $criteria->order = "t.id DESC";
                $title = 'Duyệt truyện';
            }


            if($username){
                $user = User::model()->findByAttributes(array('username' => $username));
                if(!$user)   throw new CHttpException(404,'The requested page does not exist.');
                $criteria->addCondition("t.user_id = {$user->id}");

                $title = 'Truyện cười đăng bởi '.$user->name;
            }

            $this->pageTitle = "{$title} | ". $this->siteSlogan;
            
            $dataProvider = new CActiveDataProvider('Joke', array(
                'criteria'=>$criteria,
                'pagination' => array(
                    'pageSize' => 10,
                    'pageVar' => 'page',
                ),
            ));

            $this->render('index', compact('dataProvider', 'title'));
        }
        /**
        * Displays a particular model.
        * @param integer $id the ID of the model to be displayed
        */
        public function actionView($id, $alias = NULL)
        {
            $joke = $this->loadModel($id);
        
            $joke->view++;
            $joke->update();

            $this->pageTitle = $this->ogTitle = "Truyện cười ".$joke->name .' | Truyện cười';
            $this->ogImage = $joke->imageUrl;
            if(strlen($joke->desc) > 30) $this->pageDesc = $joke->desc;

            $this->render('view',array(
                'model'=>$joke,
            ));
        }


        /**
        * Creates a new model.
        * If creation is successful, the browser will be redirected to the 'view' page.
        */
        public function actionCreate()
        {
            $model=new Video;

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['Video']))
            {
                $model->attributes=$_POST['Video'];
                if($model->save())
                    $this->redirect(array('view','id'=>$model->id));
            }

            $this->render('create',array(
                'model'=>$model,
            ));
        }

        /**
        * Updates a particular model.
        * If update is successful, the browser will be redirected to the 'view' page.
        * @param integer $id the ID of the model to be updated
        */
        public function actionUpdate($id)
        {
            $model=$this->loadModel($id);

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['Video']))
            {
                $model->attributes=$_POST['Video'];
                if($model->save())
                    $this->redirect(array('view','id'=>$model->id));
            }

            $this->render('update',array(
                'model'=>$model,
            ));
        }
        
        
        public function actionReviewed($id, $crop = false, $top = false)
        {
            $model=$this->loadModel($id);

            $model->reviewed = MyDateTime::getCurrentTime();
            $model->status = 'APPROVED';
            $model->update();
            
            if($feed = Feed::model()->findByAttributes(array('joke_id' => $model->id))){
                $feed->created = $model->reviewed;
                $feed->update();
            }else{
                $feed = new Feed();
                $feed->joke_id = $model->id;
                $feed->created = $model->reviewed;
                $feed->insert();
            }
            
            return $model;    
        }

        public function actionSocial($id, $service = 'facebook', $referrer = null)
        {
            $model = $this->actionReviewed($id);
            
            if($service == 'facebook'){
                $fbPageId = Yii::app()->params->fb['pageId'];

                Yii::import('ext.facebook.src.Facebook');
                $facebook = new Facebook(array(
                    'appId'  => Yii::app()->params->fb['appId'],
                    'secret' => Yii::app()->params->fb['secret'],
                ));

                if (!empty($_SESSION['facebook_token'])) {
                    $facebook->setAccessToken($_SESSION['facebook_token']);
//                    echo '<pre>session:';print_r($_SESSION['facebook_token']);echo '</pre>';die;
                }elseif(!empty($this->user->emailFacebook->openid_token)){
//                    echo '<pre>user:';print_r($this->user->emailFacebook->openid_token);echo '</pre>';die;
                    $_SESSION['facebook_token'] = $this->user->emailFacebook->openid_token;
                    $facebook->setAccessToken($_SESSION['facebook_token']);    
                }


                $openid_id = $facebook->getUser();

                // save access token
                if (isset($_GET['code'])) {
                    $_SESSION['facebook_token'] = $facebook->getAccessToken();
                    
                    $userEmail = UserEmail::model()->findByAttributes(array(
                        'user_id' => $this->user->id,
                        'openid_id' => $openid_id,
                    ));
                    
                    if($userEmail){
                        $userEmail->openid_token = $_SESSION['facebook_token'];
                        $userEmail->update();
                    }else{
                        $attrs = $facebook->api('/me?fields=id,name,birthday,email,gender,link');
                        $userEmail = new UserEmail();
                        $userEmail->user_id = $this->user->id;
                        $userEmail->email = $attrs['email'];
                        $userEmail->openid_id = $openid_id;
                        $userEmail->openid_service = 'FACEBOOK';
                        $userEmail->openid_token = $_SESSION['facebook_token'];
                        $userOpenid->is_main = (isset($this->user->email_main) && $this->user->email_main) ? NULL : 1;
                        $userOpenid->created = MyDateTime::getCurrentTime();
                        $userOpenid->insert();
                    }
                }
                


                // fb login url
                $fbLoginUrl = $facebook->getLoginUrl(array(
                    'scope' => 'email,user_birthday,publish_stream, manage_pages',
                    'redirect_uri' => $this->createAbsoluteUrl('/hehe/web/image/social', array(
                        'id' => $id,
                        'service' => $service,
                        'referrer' => Yii::app()->request->urlReferrer,
                    )),
                ));
                // check login
                if(!$openid_id){
                    echo json_encode(array('error' => 1, 'url' => $fbLoginUrl));
                    die;
                }
                
                // check permissons
                $permissions = $facebook->api("/me/permissions");
                if( 
                    !$openid_id || ! array_key_exists('publish_stream', $permissions['data'][0])
                    || ! array_key_exists('manage_pages', $permissions['data'][0])
                ) {
                    echo json_encode(array('error' => 1, 'url' => $fbLoginUrl));
                    die;
                }

                // check manage page
                $pages = $facebook->api(array(
                    'method' => 'fql.query', 
                    'query' => "SELECT page_id, name, page_url FROM page WHERE page_id = {$fbPageId}")
                );

                if(!$pages){
                    echo json_encode(array('error' => 1, 'msg' => 'Bạn không có quyền quản lý page'));
                    die;
                };

            // posts message on page feed
            $content = strip_tags($model->content);
            $message = "{$model->name}
            
{$model->desc}

{$content}";
            
            $msg_body = array(
                'message' => $message,
                'name' => 'Truyện cười '.$model->name,
                'link' => $model->url,
                'description' => Yii::app()->controller->siteSlogan,
                'picture' => $model->image ? $model->imageUrl : NULL,
                'actions' => array(
                    array(
                        'name' => $this->siteName,
                        'link' => $this->baseUrl
                    )
                )
            );

            //posts message on page statues
            /*
            $msg_body = array(
            'source' => '@'.realpath('myphoto/somephot.gif'),
            'message' => 'message for my wall',
            'published' => 'false', //Keep photo unpublished
            'scheduled_publish_time' => '1333699439' //Or time when post should be published
            );
            */
                $postResult = $facebook->api("/{$fbPageId}/feed", 'post', $msg_body );
                if(isset($postResult['id']) && $postResult['id']){
                    $model->fb_posted = MyDateTime::getCurrentTime();
                    $model->fb_posted_id = $postResult['id'];
                    $model->update();
                }
            }
        }

        /**
        * Deletes a particular model.
        * If deletion is successful, the browser will be redirected to the 'admin' page.
        * @param integer $id the ID of the model to be deleted
        */
        public function actionDelete($id)
        {
            $model = Joke::model()->findByPk($id);
            if(!$model) return;
            
            Feed::model()->deleteAllByAttributes(array('joke_id' => $model->id));
            
            $img_cnf = Yii::app()->params->joke_img;
            $post_path = $img_cnf['path'].$model->groupFolder.'/';

            Myext::deleteFile($post_path.$model->image.".jpg");
            
            $model->delete();

            

            if($model->fb_posted_id){

                $fbPageId = Yii::app()->params->user['fb']['pageId'];

                Yii::import('ext.facebook.src.Facebook');
                $fb = new Facebook(array(
                    'appId'  => Yii::app()->params->user['fb']['appId'],
                    'secret' => Yii::app()->params->user['fb']['secret'],
                ));

                $fb_id = $fb->getUser();

                // check login
                $fbLoginUrl = $fb->getLoginUrl(array(
                    'scope' => 'publish_stream,manage_pages',
                    'redirect_uri' => Yii::app()->request->getBaseUrl(TRUE).Yii::app()->request->requestUri,
                ));
                if(!$fb_id){
                    Yii::app()->controller->redirect($fbLoginUrl);
                }

                // check permissons
                $permissions = $fb->api("/me/permissions");
                if( 
                    !$fb_id || ! array_key_exists('publish_stream', $permissions['data'][0])
                    || ! array_key_exists('manage_pages', $permissions['data'][0])
                ) {
                    Yii::app()->controller->redirect($fbLoginUrl);
                }


                $fb->api("/{$model->fb_posted_id}","DELETE");
            }
        }


        /**
        * Manages all models.
        */
        public function actionAdmin()
        {
            $model=new Video('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Video']))
                $model->attributes=$_GET['Video'];

            $this->render('admin',array(
                'model'=>$model,
            ));
        }

        /**
        * Returns the data model based on the primary key given in the GET variable.
        * If the data model is not found, an HTTP exception will be raised.
        * @param integer the ID of the model to be loaded
        */
        public function loadModel($id)
        {
            $model=Joke::model()->findByPk($id);
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }

        /**
        * Performs the AJAX validation.
        * @param CModel the model to be validated
        */
        protected function performAjaxValidation($model)
        {
            if(isset($_POST['ajax']) && $_POST['ajax']==='video-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
        }
    }
